<template>
  <div>
    <el-form ref="formRef" :model="model" :rules="rules" label-width="140px" status-icon>
      <el-form-item label="名称" prop="title" class="w-[600px]">
        <el-input v-model="model.title" />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
const props = defineProps({
  info: { type: Object, default: {} },
})
const formRef = ref(null)
const model = ref({})

const rules = reactive({
  title: [
    { required: true, message: '请输入名称', trigger: 'blur' },
    { max: 100, message: '长度不超过100个字符', trigger: 'blur' },
  ],
})

onMounted(() => {
  if (props.info) {
    model.value = props.info
  }
})

const submit = (updateApi, form) => {
  if (!form) return
  return form.validate(async (valid, fields) => {
    if (!valid) {
      for (let item in fields) {
        ElMessage.error(fields[item][0].message)
      }
      return false
    }
    const { code } = await updateApi(model.value)
    if (code === 200) {
      ElMessage.success(model.value.id ? '修改成功' : '添加成功')
      return true
    }
  })
}

defineExpose({ submit, formRef })
</script>
